import os
import socket
import logging
import datetime
from opslog.cli.plugins import BasePlugin

class Log(BasePlugin):
    def add(self):
        if self.client.args.ENTRY:
            args={}
            args["content"] = self.client.args.ENTRY
            args["username"] = os.getlogin()
            args["hostname"] = socket.getfqdn()
            args["show_username"] = self.client.args.username
            args["show_hostname"] = self.client.args.hostname
            self.client.server_call("log",args)
   
    def ls(self):
        args={}
        args["hostname"] = self.client.args.hostname
        args["username"] = self.client.args.username
        response = self.client.server_call("ls",args)
        if response["result"] == "ok":
            entries = response["entries"]
            if entries:
                for entry in entries:
                    entry["date"] = datetime.datetime.fromtimestamp(float(entry["date"]))
                    self.logger.info("%(show_username)s@%(show_hostname)s - %(date)s : %(content)s" % entry)
            else:
                self.logger.info("No entries found.")
        else:
            self.logger.info("Error retrieving entries: %s" % response["description"])
 

    def setup_arguments(self,root_subparsers):
        log_parser = root_subparsers.add_parser("log", help="Log commands")
        log_parser.add_argument("ENTRY",nargs="?",help="Content to post")
        log_parser.add_argument("-U","--username",default=os.getlogin(),help="Intended username for log entries, default is the current login username")
        log_parser.add_argument("-H","--hostname",default=socket.getfqdn(),help="Intended hostname for log entries, default is the local fqdn")
        log_parser.set_defaults(run=self.add)
    
        ls_parser = root_subparsers.add_parser("ls",help="List commands")
        ls_parser.add_argument("-U","--username",default=os.getlogin(),help="Intended username for log entries, default is the current login username")
        ls_parser.add_argument("-H","--hostname",default=socket.getfqdn(),help="Intended hostname for log entries, default is the local fqdn")
        ls_parser.set_defaults(run=self.ls)
      
